package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private PermissionDao permissionDao;

    @Override
    public User findByUsername(String username) {
        // 1. 通过用户名获取用户信息
        /*User user = userDao.findByUsername(username);
        if(null != user) {
            // 2. 通过用户的ID获取用户所拥有的角色集合,设置给用户
            Set<Role> roles = roleDao.findByUserId(user.getId());
            if(null != roles && roles.size() > 0) {
                user.setRoles(roles);
                // 3. 遍历角色集合，通过角色编号获取权限集合, 设置给角色
                for (Role role : roles) {
                    // 通过角色编号获取这个角色所拥有的权限集合
                    Set<Permission> permissions = permissionDao.findByRoleId(role.getId());
                    role.setPermissions(permissions);
                }
            }
            return user;
        }
        return null;*/
        return userDao.findUserRolePermissionByUsername(username);
    }

    /** 获取当前用户菜单
     * @param username
     * @return
     */
    @Override
    public List<Menu> getMenu(String username) {
        List<Menu> menus = userDao.getMenu(username);
        return menus;
    }


    //分页查询
    @Override
    public PageResult<User> findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        //模糊查询需要凭借
        if(!StringUtils.isEmpty(queryPageBean.getQueryString()))
        {
            queryPageBean.setQueryString("%"+queryPageBean.getQueryString()+"%");
        }
        //使用分页插件
        PageHelper.startPage(currentPage,queryPageBean.getPageSize());
        //紧接着查询的语句会被拦截进行分页  查询所有
        Page<User> page = userDao.findByCondition(queryPageBean.getQueryString());
        //使用pageresult包装
        PageResult<User> result = new PageResult<>(page.getTotal(), page.getResult());
        return result;
    }


    //新增用户
    @Override
    @Transactional
    public void add(Integer[] roleIds, User user) {
        userDao.add(user);
        setUserAndRole(user.getId(),roleIds);
    }



    public void setUserAndRole(Integer userId, Integer[] roleIds) {
        if(roleIds!=null&&roleIds.length>0)
        {
            for (Integer roleId : roleIds) {
                Map<String,Integer> map = new HashMap<>();
                map.put("user_id",userId);
                map.put("role_id",roleId);
                userDao.setUserAndRole(map);
            }
        }
    }

    @Override
    public User findById(int id) {
        return userDao.findById(id);
    }


    //编辑用户
    @Override
    public void edit(Integer[] roleIds, User user) {
        //根据user_id 删除中间表原有的数据
        userDao.deleteAssociationUserAndRole(user.getId());
        //在中间表新增更改过后的关系
        setUserAndRole(user.getId(),roleIds);
        //更新CheckGroup表中的数据
        userDao.edit(user);
    }

    @Override
    public void deleteById(int id) {
        int count = userDao.countRoleIdsByUserId(id);
        if(count>0)
        {
            throw new RuntimeException(MessageConstant.DELETE_USER_USED);
        }
        userDao.deleteById(id);
    }





}
